package com.youyi.utils;

import com.youyi.entity.User;
import com.youyi.entity.UserDto;
import com.youyi.exception.BeanException;
import java.lang.reflect.Method;

/**
 * @author youyi.time
 * @date 2024/11/19 18:04
 */
public class BeanUtils {


    /**
     * 将source对象上的的属性赋值到target对象同样的属性中
     * 采用getter setter 方法进行复制，请确保实体存在get ，set方法，
     * 不然会失效
     * @param source
     * @param target
     */

    public static void copyProperties(Object source, Object target) {
        if(source == null || target == null) throw new BeanException("bean cannot be null");
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        // 获取源对象的所有方法
        Method[] sourceMethods = sourceClass.getMethods();
        for (Method sourceMethod : sourceMethods) {
            String methodName = sourceMethod.getName();
            // 检查是否为getter方法
            if (methodName.startsWith("get") && methodName.length() > 3) {
                // 获取对应的setter方法名称
                String setterMethodName = "set" + methodName.substring(3);
                Method targetMethod = getTargetMethod(targetClass, setterMethodName, sourceMethod.getReturnType());

                try {
                    if (targetMethod != null) {
                        // 调用源对象的getter方法
                        Object value = sourceMethod.invoke(source);
                        // 调用目标对象的setter方法
                        targetMethod.invoke(target, value);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new BeanException("copy bean is fail");
                }

            }
        }
    }

    /**
     * 得到目标方法对象
     * @param clazz
     * @param methodName
     * @param parameterType
     * @return
     */
    private static Method getTargetMethod(Class<?> clazz, String methodName, Class<?> parameterType) {
        try {
            return clazz.getMethod(methodName, parameterType);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        UserDto userDto = new UserDto();
        userDto.setAge(18);
        userDto.setUsername("用户名");
        userDto.setPassword("1234");
        System.out.println(userDto);
        User user = new User();

        System.out.println(System.currentTimeMillis());
        copyProperties(userDto ,user);
        System.out.println(System.currentTimeMillis());
        System.out.println(userDto);

    }
}
